import { Divider, Button as AntButton } from "antd";
import FormByData, { FormByDataProps } from "./FormByData/FormByData";
import { useState, useEffect, MouseEventHandler, useMemo } from "react";
import { AnyObject } from "antd/es/_util/type";
import AuthButton from "@/components/Button";

interface SearchProps<D extends AnyObject> extends FormByDataProps<D> {
    onReset?: MouseEventHandler<HTMLElement>;
    onAdd?: MouseEventHandler<HTMLElement>;
    onSearch?: FormByDataProps<D>["onSubmit"];
    title?: string;
    createPermission?: string;
    listPermission?: string;
}

const Search = <D extends AnyObject>(props: SearchProps<D>) => {
    const { title, formItems, onSubmit, onReset, actionMore, onAdd, onSearch, createPermission, listPermission, ...remainingProps } = props;
    const [cols, setCols] = useState(5);
    const handleResize = () => {
        const { innerWidth } = window;
        if (innerWidth >= 1900) return setCols(5);
        if (innerWidth >= 1500) return setCols(4);
        if (innerWidth >= 1100) return setCols(3);
        if (innerWidth >= 700) return setCols(2);
        setCols(1);
    };
    useEffect(() => {
        handleResize();
        window.addEventListener("resize", handleResize);
    }, []);

    const AddButton = useMemo(() => (createPermission ? AuthButton : AntButton), [createPermission]);
    return (
        <div className="py-4">
            {title && (
                <>
                    <h2>{title}</h2>
                    <Divider />
                </>
            )}
            <FormByData
                formItems={formItems}
                onSubmit={onSearch}
                footerPlacement="left"
                cols={cols}
                formProps={{
                    labelCol: { style: { width: "70px", display: "inline-block", flexShrink: 0 } },
                    wrapperCol: { offset: 1, span: 16 },
                }}
                footerClass="!mt-0"
                okText="搜索"
                spaceProps={{ size: "middle" }}
                actionMore={
                    <>
                        {onReset && <AntButton onClick={onReset}>重置</AntButton>}
                        {onAdd && (
                            <AddButton type="primary" onClick={onAdd} ghost {...(createPermission ? { permission: createPermission } : {})}>
                                新增
                            </AddButton>
                        )}
                        {actionMore}
                    </>
                }
                {...remainingProps}
                {...(listPermission ? { submitPermission: listPermission } : {})}
            />
        </div>
    );
};

export default Search;
